package cn.tedu.charging.user.handler;

import cn.tedu.charging.common.pojo.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;


@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult HandleMethodArgumentNotValidException (MethodArgumentNotValidException e){
        log.error("捕获MethodArgumentNotValidException",e);
        List<FieldError> fieldErrors = e.getFieldErrors();
        StringBuffer allMessage=new StringBuffer();
        for (FieldError fieldError : fieldErrors) {
            String defaultMessage = fieldError.getDefaultMessage();
            allMessage.append(defaultMessage);
        }
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode(4000);
        jsonResult.setMessage(allMessage.toString());
        return jsonResult;
    }
}
